package com.ltkj.ticket.service.impl;

import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.RemoteFileService;
import com.ltkj.system.api.domain.CommAttachment;
import com.ltkj.ticket.domain.*;
import com.ltkj.ticket.domain.dto.*;
import com.ltkj.ticket.domain.vo.*;
import com.ltkj.ticket.mapper.*;
import com.ltkj.ticket.service.IAppletTicketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Time;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AppletTicketServiceImpl implements IAppletTicketService {

    private static final Logger log = LoggerFactory.getLogger(AppletTicketServiceImpl.class);

    @Autowired
    private AppletTicketMapper appletTicketMapper;
    @Autowired
    private TicScenicMapper ticScenicMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private TicOtherBaseMapper tcOtherBaseMapper;
    @Autowired
    private TicVenuesMapper ticVenuesMapper;
    @Autowired
    private TicActivityBusinessMapper activityBusinessMapper;
    @Autowired
    private TicActivityStockMapper ticActivityStockMapper;
    @Autowired
    private TicOrderWriteoffMapper ticOrderWriteoffMapper;
    @Autowired
    private TicVenuesPeriodMapper tcVenuesPeriodMapper;


    @Value("${ticket.activity}")
    private Integer activityLimit;
    @Value("${ticket.countdown}")
    private Integer countdown;


    @Override
    public List<AppletTicketPageVo> list(AppletTicketQueryDTO queryDTO) {
        if (queryDTO.getTicketType() != null && !"".equals(queryDTO.getTicketType())) {
            if ("2".equals(queryDTO.getTicketType()) && redisService.hasKey("page_tic_act")) {
                List<AppletTicketPageVo> pageList = redisService.getCacheList("PAGE:page_tic_act");
                return pageList;
            } else {
                List<AppletTicketPageVo> list = appletTicketMapper.list(queryDTO);
                return list;
            }
        } else {
            throw new ServiceException("入参异常，请检查参数");
        }
    }

    @Override
    public AppletTicketDetailVo detail(AppletTicketDetailQueryDTO queryDTO) {
        AppletTicketDetailVo vo = new AppletTicketDetailVo();
        // 景区门票详情
        if ("1".equals(queryDTO.getTicketType())) {
            // 景区门票基础
            TicketDetailVo ticketDetailVo = appletTicketMapper.selectTickeDetail(queryDTO);
            ticketDetailVo.setTicketType(queryDTO.getTicketType());
            vo.setTicketDetailVo(ticketDetailVo);
            // 门票图片
            TicScenic ticScenic = ticScenicMapper.selectTicScenicByScenicId(queryDTO.getTicketId());
            List<String> pics = appletTicketMapper.selectTicketPics(ticScenic.getTicOtherId());
            vo.setTicketPics(pics);
            // 游览时间
            queryDTO.setTicketActivityLimit(activityLimit);
            List<TicketTourVo> tourVos = appletTicketMapper.selectTourVos(queryDTO);
            if (tourVos != null && tourVos.size() > 0) {
                for (TicketTourVo tourVo : tourVos) {
                    // 获取每天票种信息
                    List<TicketTypeVo> list = appletTicketMapper.selectTictkeTypes(tourVo.getStockDate(), queryDTO.getTicketId());
                    tourVo.setVoList(list);
                }
            }
            vo.setTourTime(tourVos);
        } else if ("2".equals(queryDTO.getTicketType())) {
            // 活动门票基础
//            vo = redisService.getCacheObject("DETAIL:HD_" + queryDTO.getTicketId());
            //查询详情放
            TicketDetailVo ticketDetailVo = ticActivityStockMapper.selectDetailById(queryDTO.getTicketId());
            vo.setTicketDetailVo(ticketDetailVo);
            //轮播图
            TicActivityBusiness ticActivityBusiness = activityBusinessMapper.selectTicActivityBusinessByActivityId(queryDTO.getTicketId());
            List<String> pics = ticActivityStockMapper.selectTicketPics(ticActivityBusiness.getTicOtherId());
            vo.setTicketPics(pics);
            // 游览时间
            queryDTO.setTicketActivityLimit(activityLimit);
            List<TicketTourVo> tourVos = ticActivityStockMapper.selectTourVos(queryDTO);
            if(tourVos!=null&&tourVos.size()>0){
                for (TicketTourVo tourVo:tourVos) {
                    //获取每天票种信息
                    List<TicketTypeVo> list = ticActivityStockMapper.selectTictkeTypes(tourVo.getStockDate(),queryDTO.getTicketId());
                    tourVo.setVoList(list);
                }
            }
            vo.setTourTime(tourVos);
        } else {
            throw new ServiceException("参数错误。请检查参数！");
        }
        return vo;
    }

    @Override
    public List<AppletOrderPageVo> listOrder(AppletOrderQueryDTO queryDTO) {
        queryDTO.setUserId(SecurityUtils.getUserId());
        List<AppletOrderPageVo> list = appletTicketMapper.listOrder(queryDTO);
        if (list != null && list.size() > 0) {
            for (AppletOrderPageVo orderPageVo : list) {
                List<AppletOrderDetailPageVo> detailPageVoList = appletTicketMapper.detailOrderByOrderId(orderPageVo.getOrderId());
                orderPageVo.setDetailPageVoList(detailPageVoList);
            }
        }
        return list;
    }

    @Override
    public List<AppletOrderPageVo> listOrderNew(AppletOrderNewQueryDTO queryDTO) {
        queryDTO.setUserId(SecurityUtils.getUserId());
        if (queryDTO.getOrderType() == null || "".equals(queryDTO.getOrderType())) {
            throw new ServiceException("订单类型参数异常，请重新操作");
        }
        String[] arr = queryDTO.getOrderType().split(",");
        List<AppletOrderPageVo> list = appletTicketMapper.listOrderNew(queryDTO, arr);
        if (list != null && list.size() > 0) {
            for (AppletOrderPageVo orderPageVo : list) {
                List<AppletOrderDetailPageVo> detailPageVoList = appletTicketMapper.detailOrderByOrderId(orderPageVo.getOrderId());
                orderPageVo.setDetailPageVoList(detailPageVoList);
            }
        }
        return list;
    }

    @Override
    public List<AppletOrderVenuesPageVo> listOrderVenues(AppletOrderVenuesQueryDTO queryDTO) {

        if (queryDTO.getOrderType() == null || "".equals(queryDTO.getOrderType())) {
            throw new ServiceException("订单类型参数异常，请重新操作");
        }
        // 查询订单列表信息
        List<AppletOrderVenuesPageVo> list = appletTicketMapper.listOrderVenues(queryDTO);
        if (list != null && list.size() > 0) {

            for (AppletOrderVenuesPageVo orderPageVo : list) {
                orderPageVo.setOrderTotalPrice(orderPageVo.getOrderTotalPrice().divide(new BigDecimal("100"), 2));

                List<AppletOrderVenuesDetailsPageVo> detailPageVoList = appletTicketMapper.detailOrderVenuesByOrderId(orderPageVo.getOrderId());
                if (detailPageVoList != null && detailPageVoList.size() > 0) {
                    TicVenues ticVenues = ticVenuesMapper.selectTicVenuesByVenuesId(detailPageVoList.get(0).getVenuesid());
                    if (ticVenues != null) {
                        orderPageVo.setVenuesPhone(ticVenues.getVenuesPhone());
                    }

                    if (StringUtils.isEmpty(orderPageVo.getImgUrl())) {
                        List<CommAttachment> ticOtherBaseImg = remoteFileService.selectAtta(detailPageVoList.get(0).getTicOtherBaseId(), "tic_other_base_img");
                        if (ticOtherBaseImg != null && ticOtherBaseImg.size() > 0) {
                            orderPageVo.setImgUrl(ticOtherBaseImg.get(0).getAttaPath());
                        }
                    }

                }
                orderPageVo.setDetailPageVoList(detailPageVoList);
            }
        }

        return list;
    }

    @Override
    public AppletOrderVenuesPageVo detailVenuesOrder(AppletOrderDetailQueryDTO queryDTO) {
        // 查询订单列表信息
        AppletOrderVenuesPageVo orderPageVo = appletTicketMapper.listOrderVenuesByOrderIdOrOrderNUm(queryDTO);
        if (orderPageVo.getOrderStatus().equals("1")) {
            // 判断当前时间到结束到期时间
            Date createTime = orderPageVo.getOrderTime();
            Date date = DateUtils.timeProcess(createTime, Calendar.MINUTE, countdown);
            long l = DateUtils.getDistanceDateTime(new Date() ,date, 4);
            orderPageVo.setResidueTimeNum(l);

        }


        orderPageVo.setOrderTotalPrice(orderPageVo.getOrderTotalPrice().divide(new BigDecimal("100"), 2));

        List<AppletOrderVenuesDetailsPageVo> detailPageVoList = appletTicketMapper.detailOrderVenuesByOrderId(orderPageVo.getOrderId());
        if (detailPageVoList != null && detailPageVoList.size() > 0) {
            if (StringUtils.isEmpty(orderPageVo.getImgUrl())) {
                List<CommAttachment> ticOtherBaseImg = remoteFileService.selectAtta(detailPageVoList.get(0).getTicOtherBaseId(), "tic_other_base_img");
                if (ticOtherBaseImg != null && ticOtherBaseImg.size() > 0) {
                    orderPageVo.setImgUrl(ticOtherBaseImg.get(0).getAttaPath());
                }
                if (StringUtils.isEmpty(orderPageVo.getLatitude())) {
                    // 查询场馆信息
                    TicOtherBase ticOtherBase = tcOtherBaseMapper.selectTicOtherBaseByTicOtherId(detailPageVoList.get(0).getTicOtherBaseId());
                    if (ticOtherBase != null) {
                        orderPageVo.setLatitude(ticOtherBase.getLatitude());
                        orderPageVo.setLongitude(ticOtherBase.getLongitude());
                        orderPageVo.setAddressDetails(ticOtherBase.getAddressDetails());
                        orderPageVo.setIntroduceDetails(ticOtherBase.getIntroduceDetails());
                        orderPageVo.setTouristNotice(ticOtherBase.getTouristNotice());
                    }
                }
                if (StringUtils.isEmpty(orderPageVo.getVenuesPhone())) {
                    // 查询门票信息
                    TicVenues ticVenues = ticVenuesMapper.selectTicVenuesByVenuesId(detailPageVoList.get(0).getVenuesid());
                    if (ticVenues != null) {
                        orderPageVo.setVenuesPhone(ticVenues.getVenuesPhone());
                    }
                }
            }

        }
        orderPageVo.setDetailPageVoList(detailPageVoList);


        return orderPageVo;
    }

    @Override
    public AppletOrderDetailVo detailOrder(AppletOrderDetailQueryDTO queryDTO) {
        AppletOrderDetailVo vo = appletTicketMapper.detailOrder(queryDTO);
        if (vo.getOrderStatus().equals("1")) {
            // 判断当前时间到结束到期时间
            Date createTime = vo.getOrderTime();
            Date date = DateUtils.timeProcess(createTime, Calendar.MINUTE, countdown);
            long l = DateUtils.getDistanceDateTime(new Date() ,date, 4);
            vo.setResidueTimeNum(l);

        }
        if (vo != null) {
            List<AppletOrderDetaildVo> detaildVoList = appletTicketMapper.detailOrderDetailByOrderId(vo.getOrderId());
            vo.setDetaildVoList(detaildVoList);
        }
        return vo;
    }

    @Override
    public AjaxResult paySucessStatus(Long orderId) {
        // 更新订单和分订单状态为已支付
        appletTicketMapper.payOrderStatus(orderId, "2");
        appletTicketMapper.payOrderDetailStatus(orderId, "2");
        return AjaxResult.success();
    }

    @Override
    public AjaxResult ticCheckStatus(String orderNum) {
        String status = appletTicketMapper.selectTicCheckStatus(orderNum);
        if (status == null || "".equals(status)) {
            throw new ServiceException("订单状态异常，无法核销");
        }
        if ("4".equals(status)) {
            throw new ServiceException("订单已核销，请勿重复核销");
        }
        List<OrderDetailsVo> list = appletTicketMapper.selectTicOrderDetailByOrderNum(orderNum);
        if (list != null&&list.size()>0) {
            for (OrderDetailsVo detail:list) {
                if ("1".equals(detail.getOrderTicketType())||"2".equals(detail.getOrderTicketType())){
                    if (DateUtils.getCompareToDate(detail.getTicketDate())!=0){
                        return AjaxResult.error("该票使用日期与当前日期不符，无法核销！");
                    }
                }else if("3".equals(detail.getOrderTicketType())){
                    if (DateUtils.getCompareToDate(detail.getTicketDate())!=0){
                        return AjaxResult.error("该票使用日期与当前日期不符，无法核销！");
                    }
                    //查询场馆时间段
                    TicVenuesPeriod ticVenuesPeriod = tcVenuesPeriodMapper.selectTicVenuesPeriodByPeriodId(detail.getTicVenuesPeriodId());
                    if(ticVenuesPeriod== null){
                        return AjaxResult.error("该票不存在，无法核销！");
                    }
                    Time periodTimeEnd = ticVenuesPeriod.getPeriodTimeEnd();
                    Date dateTime = DateUtils.getDateTime(detail.getTicketDate(), periodTimeEnd);
                    int i1 = DateUtils.dateCompare(new Date(), dateTime);
                    if (i1==1){
                        return AjaxResult.error("该票使用时间晚于预约结束时间，无法核销！");
                    }

                }
            }
        }
        // 更新订单和分订单状态为已核销
        appletTicketMapper.payOrderStatusByOrderNum(orderNum, "4");
        appletTicketMapper.payOrderDetailStatusByOrderNum(orderNum, "4");
        //添加核销记录
        TicOrderWriteoff ticOrderWriteoff = new TicOrderWriteoff();
        ticOrderWriteoff.setOrderNum(orderNum);
        ticOrderWriteoff.setWriteOffUser(SecurityUtils.getUserId());
        ticOrderWriteoff.setWriteOffTime(new Date());
        ticOrderWriteoff.setCreateTime(new Date());
        ticOrderWriteoffMapper.insertTicOrderriteoff(ticOrderWriteoff);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult cancleOrder(Long orderId) {
        // 更新订单和分订单状态为取消
        appletTicketMapper.payOrderStatus(orderId,"3");
        appletTicketMapper.payOrderDetailStatus(orderId, "3");
        //优惠券回退
        appletTicketMapper.updateUserCouponByOrderId(orderId);
        List<OrderDetailsVo> list = appletTicketMapper.selectTicOrderDetailByOrderId(orderId);
        if (list!=null&&list.size()>0){
            for (OrderDetailsVo detail:list) {
                if ("2".equals(detail.getOrderTicketType())) {
                    String goodsId = "STOCK:HD_" + detail.getTicketId() + "_" + DateUtils.parseDateToStr("yyyy-MM-dd", detail.getTicketDate()) +"_"+ detail.getUserId();
                    redisService.deleteObject(goodsId);
                }else if("1".equals(detail.getOrderTicketType())){
                    //景区库存回退
                    TicStockDateVo ticStockDateVo = appletTicketMapper.selectTicStockDate(detail.getTicConfigId());
                    //回退数据库库存
                    appletTicketMapper.updateStockCountByStockDate(ticStockDateVo.getTicketId(), detail.getTicketCount(), ticStockDateVo.getStockDate());
                }else if("3".equals(detail.getOrderTicketType())){
                    //回退数据库库存
                    Long ticVenuesPeriodId = detail.getTicVenuesPeriodId();
                    log.info("回退数据库库存",detail.toString());
                    appletTicketMapper.updateVenuesPeriodCount(ticVenuesPeriodId,1);                          }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult cancleVenuesOrder(Long orderId) {
        appletTicketMapper.updateOrderStatus(orderId, "3");
        //redis中该用户重复购买标识去掉
        List<OrderDetailsVo> list = appletTicketMapper.selectTicOrderDetailByOrderId(orderId);
        if (list!=null&&list.size()>0){
            for (OrderDetailsVo detail:list) {
                appletTicketMapper.updateVenuesPeriodCount(detail.getTicVenuesPeriodId(),detail.getTicketCount());
                if ("2".equals(detail.getOrderTicketType())) {
                    String goodsId = "STOCK:HD_" + detail.getTicketId() + "_" + DateUtils.parseDateToStr("yyyy-MM-dd", detail.getTicketDate()) +"_"+ detail.getUserId();
                    redisService.deleteObject(goodsId);
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteOrder(Long orderId) {
        //
        appletTicketMapper.deleteOrder(orderId);
        appletTicketMapper.deleteOrderDetail(orderId);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult backfill(Long orderDetailId, String trackingCode) {
        appletTicketMapper.backfill(orderDetailId, trackingCode);
        return AjaxResult.success();
    }
}
